package org.sample.controller;

import org.sample.model.APIResult;
import org.sample.dao.GroupDao;
import org.sample.entity.Group;
import org.sample.service.GroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("manage/group")
public class GroupController {

    @Autowired
    private GroupDao groupDao;

    @Autowired
    private GroupService groupService;

    @RequestMapping(path = {"edit", "add"}, method = RequestMethod.GET)
    public String edit(Group entity, Model model) {
        Integer id = entity.getId();
        if (id != null) {
            entity = groupDao.getOne(id);
        }
        model.addAttribute("entity", entity);
        return "group/edit";
    }

    @RequestMapping(path = "update", method = RequestMethod.POST)
    public String update(Group entity) {
        groupService.saveNotNull(entity);
        return "redirect:edit?id=" + entity.getId();
    }

    @RequestMapping(path = "remove", method = RequestMethod.POST)
    @ResponseBody
    public APIResult remove(Integer id) {
        groupService.logicalDelete(id);
        return new APIResult();
    }

    @RequestMapping("list")
    public String list(@RequestParam(required = false, defaultValue = "1") int pageNo,
                       @RequestParam(required = false, defaultValue = "10") int pageSize,
                       Group entity, Model model) {
        Pageable pageable = PageRequest.of(pageNo - 1, pageSize);
        Page<Group> page = groupDao.findAll(Example.of(entity), pageable);
        model.addAttribute("page", page);

        model.addAttribute("entity", entity);
        return "group/list";
    }

}